package com.gemme.gemme.wode;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.gwc.GwcBean;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.util.OrderInfoUtil2_0;
import com.gemme.gemme.util.UMSharePlatform;
import com.gemme.gemme.view.Topview;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//侧滑删除地址
public class TestUMengActivity extends BaseActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_ali);
        initTop();
        //判断是否已经获取到了权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //没有的话弹出权限获取框
//            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
            if(Build.VERSION.SDK_INT>=23){
                String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
                ActivityCompat.requestPermissions(this,mPermissionList,123);
            }
        }

        initView();
    }
    EditText et_accessToken;
    private void initView() {
        et_accessToken = findViewById(R.id.et_accessToken);
        findViewById(R.id.weixin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("");
                UMShareAPI.get(mContext).getPlatformInfo(TestUMengActivity.this, SHARE_MEDIA.WEIXIN, new UMAuthListener(){

                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        System.out.println("");
                        System.out.println("");
                        et_accessToken.setText(map.get("accessToken") + "");
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        System.out.println("");
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {

                    }
                });
            }
        });


        shares();

        weixinzhifu();
    }

    private void weixinzhifu() {
        findViewById(R.id.weixin_zhifu).setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                final IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
               /* WeChatPayEntity weChatPayEntity = new Gson().fromJson(data, new TypeToken<WeChatPayEntity>() {
                }.getType());
                if (weChatPayEntity == null) {
                    return;
                }
                String appId = weChatPayEntity.getAppid();
                if (!TextUtils.isEmpty(appId)) {
                    // 将该app注册到微信
                    msgApi.registerApp(appId);
                    PayReq req = new PayReq();
                    App.appId = appId;
                    req.appId = appId;
                    req.partnerId = weChatPayEntity.getPartnerid();
                    req.prepayId = weChatPayEntity.getPrepayid();
                    req.packageValue = weChatPayEntity.getPackageX();
                    req.nonceStr = weChatPayEntity.getNoncestr();
                    req.timeStamp = weChatPayEntity.getTimestamp();
                    req.sign = weChatPayEntity.getPaySign();
                    boolean result = msgApi.sendReq(req);
//                    Log.d(TAG, "payWechat: result:"+result);
                }*/

            }
        });
    }

    private void shares() {

        System.out.println();
        UMImage image = new UMImage(mContext, "http://img.jj20.com/up/allimg/mx12/0F420215546/200F4215546-0-lp.jpg");//网络图片
        UMWeb web = new UMWeb("https://new.qq.com/omn/20200709/20200709A05NXP00.html");
        web.setTitle("创造营");//标题
        web.setThumb(image);  //缩略图
        web.setDescription("小姐姐创造营pick u");//描述
        findViewById(R.id.weixin_fenxiang).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                userShareSaveData("WEChAT","https://new.qq.com/omn/20200709/20200709A05NXP00.html");

                new ShareAction(mContext)
                        .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                        .withText("hello")//分享内容
                        .withMedia(web)
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {
                                System.out.println("分享 : onStart");
                            }

                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                System.out.println("分享 : onResult");
                            }

                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                System.out.println("分享 : onError");
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {
                                System.out.println("分享 : onCancel");
                            }
                        })//回调监听器
                        .share();
            }
        });
    }

    private void userShareSaveData(String type, String h5_url) {
        SharedPreferences MSP = getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
        String access_token = MSP.getString(Constant.ACCESS_TOKEN, "").trim();
        if(TextUtils.isEmpty(type) || TextUtils.isEmpty(h5_url)|| TextUtils.isEmpty(access_token))
            return;
        String url = DataManager.BaseUrl + "user/share/goshare?";
        url = url +
                "createTime="+
                "&delFlag="+
                "&id="+
                "&sharedUserId="+
                "&status="+
                "&type="+type+
                "&updateTime="+
                "&url="+h5_url+
                "&userId="

        ;
        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put(DataManager.AuthorizationKey,"Bearer " + access_token);
        DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headHashMap, new DataManager.GeResponse(){

            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jb = new JSONObject(response);
                    int data = jb.getInt("data");
                    System.out.println("");
                    userShareSaveData2(data);
                }catch (Exception e){

                }
            }
        });
    }

    private void userShareSaveData2(int data) {
        SharedPreferences MSP = getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
        String access_token = MSP.getString(Constant.ACCESS_TOKEN, "").trim();
        if(TextUtils.isEmpty(access_token))
            return;
        String url = DataManager.BaseUrl + "user/share/sharesuccess?shareId=" + data;

        HashMap<String, String> headHashMap = new HashMap<>();
        headHashMap.put(DataManager.AuthorizationKey,"Bearer " + access_token);
        DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headHashMap, new DataManager.GeResponse(){

            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jb = new JSONObject(response);
                    int data = jb.getInt("code");
//                    if(data == 0)
//                        Toast.makeText(TestUMengActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                    System.out.println("");
                }catch (Exception e){

                }
            }
        });
    }

    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("友盟测试");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}